// main.js

// 初始化画布
const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext("2d");

// 游戏状态
const START = 0;
const STARTING = 1;
const RUNNING = 2;
const PAUSE = 3;
const END = 4;

// 定义状态常量
let state = START;

// 初始化分数
let score = 0;
let life = 3;
let Firepower = 100;
let bomb = 0;

// 敌机刷新时间
let ENEMY_CREATE_INTERVAL = 800;
// 敌机初始化时间
let ENEMY_LASTTIME = new Date().getTime();
// 敌机容器
const EnemyList = [];
let bullet = 'Bullet1';

// 实例化天空类
const sky = new Sky(SkyConfig);
// 实例化加载类
const loading = new Loading(LoadingConfig);
// 实例化英雄类
let hero = new Hero(HeroConfig);

// 使用炸弹
let isbombExploding = false;
let bombExplosionFrame = 0;
let bombExplosionX = 0;
let bombExplosionY = 0;

function usebomb() {
  if (bomb > 0 && !isbombExploding) {
    bomb--;
    EnemyList.length = 0; // 清除屏幕上的所有敌机
    isbombExploding = true;
    bombExplosionFrame = 0;
    bombExplosionX = canvas.width / 2 - bombExplosionImgs[0].width / 2;
    bombExplosionY = canvas.height / 2 - bombExplosionImgs[0].height / 2;
  }
}

// 监听键盘事件
document.addEventListener("keydown", (e) => {
  if (e.code === "Space") {
    usebomb();
  }
});

document.addEventListener("keydown", (e) => {
  // 监听箭头键移动英雄
  if (e.code === "ArrowUp") {
    hero.move(hero.x, hero.y - 10);  // 上移
  } else if (e.code === "ArrowDown") {
    hero.move(hero.x, hero.y + 10);  // 下移
  } else if (e.code === "ArrowLeft") {
    hero.move(hero.x - 10, hero.y);  // 左移
  } else if (e.code === "ArrowRight") {
    hero.move(hero.x + 10, hero.y);  // 右移
  } else if (e.code === "KeyB") {
    hero.bulletClass = Bullet2;  // 切换子弹类型为Bullet2
    hero.bulletConfig = Bullet2Config;  // 设置子弹配置为Bullet2Config
    bullet = 'Bullet2';
  }
});

document.addEventListener("keyup", (e) => {
  if (e.code === "KeyB") {
    hero.bulletClass = Bullet;
    hero.bulletConfig = Bullet1Config;
    bullet = 'Bullet1';
  }
});

// 开始状态 -> 开始时状态
canvas.addEventListener("click", () => {
  if (state === START) {
    state = STARTING;
  }
});

// 运行时状态
canvas.addEventListener("mousemove", (e) => {
  let x = e.offsetX;
  let y = e.offsetY;
  hero.x = x - hero.width / 2;
  hero.y = y - hero.height / 2;
});

// 监听暂停状态
canvas.addEventListener("mouseleave", () => {
  if (state === RUNNING) {
    state = PAUSE;
  }
});
canvas.addEventListener("mouseenter", () => {
  if (state === PAUSE) {
    state = RUNNING;
  }
});

// 碰撞检测
function checkhit() {
  for (let i = 0; i < EnemyList.length; i++) {
    if (EnemyList[i].hit(hero)) {  // 检测敌机与英雄碰撞
      if (EnemyList[i].type == 3) {  // 检测是否为炸弹补给
        bomb++;  // 增加炸弹数量
      } else if (EnemyList[i].type == 4) {  // 检测是否为子弹补给
        Firepower += 10;  // 增加火力值
      } else {
        EnemyList[i].collide(bullet);  // 敌机碰撞处理
        hero.collide();  // 英雄碰撞处理
      }
      EnemyList.splice(i, 1);  // 移除碰撞的敌机
      i--;  // 调整索引
      continue;
    }
    for (let j = 0; j < hero.bulletList.length; j++) {
      if (EnemyList[i].hit(hero.bulletList[j])) {  // 检测敌机与子弹碰撞
        EnemyList[i].collide(bullet);  // 敌机碰撞处理
        hero.bulletList[j].collide();  // 子弹碰撞处理
        if (EnemyList[i].type == 3) {  // 检测是否为炸弹补给
          bomb++;  // 增加炸弹数量
        } else if (EnemyList[i].type == 4) {  // 检测是否为子弹补给
          Firepower += 10;  // 增加火力值
        }
        hero.bulletList.splice(j, 1);
        j--;
        if (EnemyList[i].destroy) {
          EnemyList.splice(i, 1);
          i--;
          break;
        }
      }
    }
  }
}

// 全局函数，创建敌机
function createEnemy() {
  const currentTime = new Date().getTime();
  if (currentTime - ENEMY_LASTTIME > ENEMY_CREATE_INTERVAL) {
    // 敌机产生率
    let p = Math.floor(Math.random() * 100);
    if (p < 70) {
      EnemyList.push(new Enemy(e1Config));
    } else if (p < 90) {
      EnemyList.push(new Enemy(e2Config));
    } else if (p < 95) {
      EnemyList.push(new Enemy(bombSupplyConfig));
    } else {
      EnemyList.push(new Enemy(bulletSupplyConfig));
    }
    ENEMY_LASTTIME = currentTime;
  }
}

// 全局函数，判断子弹/敌人组件
function judgeComponent() {
  for (let i = 0; i < hero.bulletList.length; i++) {
    hero.bulletList[i].move();
  }
  for (let i = 0; i < EnemyList.length; i++) {
    EnemyList[i].move();
  }
}

// 全局函数，绘制子弹/敌人组件
function paintComponent(context) {
  for (let i = 0; i < hero.bulletList.length; i++) {
    hero.bulletList[i].paint(context);
  }
  for (let i = 0; i < EnemyList.length; i++) {
    EnemyList[i].paint(context);
  }
}

// 全局函数，销毁子弹/敌人组件
function destroyComponent() {
  if (hero.destroy) {
    life--;
    hero.destroy = false;
    if (life === 0) {
      state = END;
      endGame();
    } else {
      hero = new Hero(HeroConfig);
    }
  }
  for (let i = 0; i < hero.bulletList.length; i++) {
    if (hero.bulletList[i].outOfBounds() || hero.bulletList[i].destroy) {
      hero.bulletList.splice(i, 1);
    }
  }
  for (let i = 0; i < EnemyList.length; i++) {
    if (EnemyList[i].outOfBounds() || EnemyList[i].destroy) {
      EnemyList.splice(i, 1);
    }
  }
}

// 游戏控制函数
function startGame() {
  document.getElementById("start-screen").style.display = "none";
  document.querySelector(".stage").style.display = "block";
  state = STARTING;
}

function pauseGame() {
  state = PAUSE;
  document.getElementById("pause-screen").style.display = "flex";
}

function resumeGame() {
  state = RUNNING;
  document.getElementById("pause-screen").style.display = "none";
}

function restartGame() {
  document.getElementById("pause-screen").style.display = "none";
  document.getElementById("end-screen").style.display = "none";
  document.getElementById("pauseButton").style.display = "none";
  score = 0;
  life = 3;
  Firepower = 100;
  bomb = 0;
  EnemyList.length = 0;
  hero = new Hero(HeroConfig);
  state = STARTING;
}

function endGame() {
  state = END;
  document.getElementById("pause-screen").style.display = "none";
  document.getElementById("current-score").innerText = score;
  document.getElementById("pauseButton").style.display = "none";
  const token = localStorage.getItem("token");
  axios
    .get(`http://localhost:4407/api/User/SaveScore?score=${score}`, {
      headers: {
        Authorization: `${token}`,
      },
    })
    .then((response) => {
      const data = response.data;
      if (data.msg === "成功") {
        document.getElementById("high-score").innerText = data.TopScore;
      } else {
        alert("无法获取游戏数据: " + data.msg);
      }
    })
    .catch((error) => console.error("Error:", error));

  axios
    .get("http://localhost:4407/api/User/GetTopUser")
    .then((response) => {
      const data = response.data;
      if (data.msg === "成功") {
        const leaderboard = data.TopUserList;
        const leaderboardElement = document.getElementById("leaderboard");
        leaderboardElement.innerHTML = "";
        leaderboard.forEach((player) => {
          const li = document.createElement("li");
          li.innerText = `玩家${player.username}：${player.score}`;
          leaderboardElement.appendChild(li);
        });
        document.getElementById("end-screen").style.display = "flex";
      } else {
        alert("无法获取游戏数据: " + data.msg);
      }
    })
    .catch((error) => console.error("Error:", error));
}
// 当图片加载完毕时，需要执行的逻辑
bg.addEventListener(
  "load",
  () => {
    setInterval(() => {
      switch (state) {
        case START:
          document.getElementById("end-screen").style.display = "none";
          sky.judge();
          sky.paint(ctx);
          let logo_x = (sky.width - logo.naturalWidth) / 2;
          let logo_y = (sky.height - logo.naturalHeight) / 2;
          ctx.drawImage(logo, logo_x, logo_y);
          break;
        case STARTING:
          document.getElementById("end-screen").style.display = "none";
          sky.judge();
          sky.paint(ctx);
          loading.judge();
          loading.paint(ctx);
          break;
        case RUNNING:
          document.getElementById("pauseButton").style.display = "block";
          sky.judge();
          sky.paint(ctx);
          ctx.font = "20px white";
          ctx.fillStyle = "white";
          ctx.textAlign = "left";
          ctx.fillText("得分: " + score, 10, 25);
          ctx.textAlign = "left";
          ctx.fillText("生命: " + life, 10, 60);
          ctx.textAlign = "right";
          ctx.fillText("炸弹数: " + bomb, 650 - 10, 25);
          ctx.textAlign = "right";
          ctx.fillText("火力值: " + Math.max(Firepower, 0), 650 - 10, 60); // 确保火力值不为负
          hero.judge();
          hero.paint(ctx);
          hero.shot(ctx);
          createEnemy();
          judgeComponent();
          paintComponent(ctx);
          destroyComponent();
          checkhit();
          if (isbombExploding) {
            if (bombExplosionFrame < bombExplosionImgs.length) {
              ctx.drawImage(
                bombExplosionImgs[bombExplosionFrame],
                bombExplosionX,
                bombExplosionY
              );
              bombExplosionFrame++;
            } else {
              isbombExploding = false;
            }
          }
          break;
        case PAUSE:
          let pause_x = (sky.width - pause.naturalWidth) / 2;
          let pause_y = (sky.height - pause.naturalHeight) / 2;
          ctx.drawImage(pause, pause_x, pause_y);
          break;
        case END:
          ctx.textAlign = "center";
          ctx.textBaseline = "middle";
          ctx.fillStyle = "#ffffff";
          ctx.font = "bold 60px red";
          ctx.fillText("GAME           OVER", 650 / 2, 850 / 2);
          // endGame();
          break;
      }
    }, 10);
  },
  false
);
